package com.jse;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Streams {
	
	public final static int BUF_SIZE=8192;

	public static long copy(String in,String out) {
		try {
			return copy(new FileInputStream(in),new FileOutputStream(out),0);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static long copy(File in,File out) {
		try {
			return copy(new FileInputStream(in),new FileOutputStream(out),0);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 拷贝流，使用NIO，不会关闭流
	 *
	 * @param in             {@link ReadableByteChannel}
	 * @param out            {@link WritableByteChannel}
	 * @param bufferSize     缓冲大小，如果小于等于0，使用默认
	 * @param progress {@link progress}进度处理器
	 * @return 拷贝的字节数
	 * @throws IORuntimeException IO异常
	 */
	public static long copy(InputStream in, OutputStream out, int bufferSize){
		ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize <= 0 ? 8192 : bufferSize);
		long size = 0;
		try {
			WritableByteChannel outs=Channels.newChannel(out);
			ReadableByteChannel cin=Channels.newChannel(in);
			while (cin.read(byteBuffer) != -1) {
				byteBuffer.flip();// 写转读
				size += outs.write(byteBuffer);
				byteBuffer.clear();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return size;
	}

	public static void close(Object...col) {
		if (null != col) {
			try {
				for (Object a : col) {
					if(a!=null) {
						if(a instanceof AsynchronousSocketChannel) {
							AsynchronousSocketChannel channel=(AsynchronousSocketChannel) a;
							try {channel.shutdownInput();}catch(IOException e) {}
							try {channel.shutdownOutput();}catch(IOException e){}
							try {channel.close();} catch (IOException e) {}
						}else if(a instanceof AutoCloseable) {
							((AutoCloseable)a).close();
						}else if(a instanceof URLConnection) {
							if (a instanceof HttpURLConnection) {
					            ((HttpURLConnection) a).disconnect();
					        }
							a=null;
						}
						
					}
				}
			} catch (Exception e) {
				// 静默关闭
			}
		}
	}
	
	/**
     * 从一个文本流中读取全部内容并返回
     * <p>
     * <b style=color:red>注意</b>，它并不会关闭输出流
     * 
     * @param reader
     *            文本输出流
     * @return 文本内容
     * @throws IOException
     */
    public static StringBuilder read(Reader reader) throws IOException {
        StringBuilder sb = new StringBuilder();
        read(reader, sb);
        return sb;
    }

    /**
     * 从一个文本流中读取全部内容并返回
     * <p>
     * <b style=color:red>注意</b>，它会关闭输入流
     * 
     * @param reader
     *            文本输入流
     * @return 文本内容
     * @throws IOException
     */
    public static String readAndClose(Reader reader) {
        try {
            return read(reader).toString();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            close(reader);
        }
    }
    
    /**
     * 从一个文本流中读取全部内容并写入缓冲
     * <p>
     * <b style=color:red>注意</b>，它并不会关闭输出流
     * 
     * @param reader
     *            文本输出流
     * @param sb
     *            输出的文本缓冲
     * @return 读取的字符数量
     * @throws IOException
     */
    public static int read(Reader reader, StringBuilder sb) throws IOException {
        char[] cbuf = new char[BUF_SIZE];
        int count = 0;
        int len;
        while (-1 != (len = reader.read(cbuf))) {
            sb.append(cbuf, 0, len);
            count += len;
        }
        return count;
    }

	public static byte[] readBytes(InputStream in){
		ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        try {
        	while (-1 != (n = in.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
     * 将一个字节数组写入一个输出流。
     * <p>
     * <b style=color:red>注意</b>，它并不会关闭输出流
     * 
     * @param ops
     *            输出流
     * @param bytes
     *            字节数组
     * @throws IOException
     */
    public static void write(OutputStream ops, byte[] bytes) throws IOException {
        if (null == ops || null == bytes || bytes.length == 0)
            return;
        ops.write(bytes);
    }

    /**
     * 将文本输入流写入一个文本输出流。块大小为 8192
     * <p>
     * <b style=color:red>注意</b>，它并不会关闭输入/出流
     * 
     * @param writer
     *            输出流
     * @param reader
     *            输入流
     * @throws IOException
     */
    public static long write(Writer writer, Reader reader) throws IOException {
        if (null == writer || null == reader)
            return 0;

        char[] cbuf = new char[BUF_SIZE];
        int len, count = 0;
        while (true) {
            len = reader.read(cbuf);
            if (len == -1)
                break;
            writer.write(cbuf, 0, len);
            count += len;
        }
        return count;
    }
    public static long write(Reader reader,Writer writer) throws IOException {
    	return write(writer,reader);
    }
    
    /**
     * 根据一段文本模拟出一个输入流对象
     *
     * @param cs
     *            文本
     * @return 输出流对象
     */
    public static InputStream ins(CharSequence cs) {
        return new ByteArrayInputStream(cs.toString().getBytes(StandardCharsets.UTF_8));
    }

	public static byte[] readBytes(File file) {
		try {
			return readBytes(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static Reader classReader(String res) {
		return new InputStreamReader(Jse.class.getResourceAsStream(res));
	}
	
	public static Reader fileReader(String file) {
		try {
			return new InputStreamReader(new FileInputStream(file),StandardCharsets.UTF_8);
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	public static long copy(InputStream in, OutputStream out) {
		return copy(in, out, BUF_SIZE);
	}

	public static List<String> readLines(InputStream in, Charset charset) {
		return readLines(in, charset, new ArrayList<String>());
	}
	public static List<String> readLines(InputStream in, Charset charset,List<String> list) {
		try(BufferedReader reader=new BufferedReader(new InputStreamReader(in,charset))){
	        String tempString = null;
	        while ((tempString = reader.readLine()) != null){
	            list.add(tempString);
	        }
	    }catch(IOException e){
	        e.printStackTrace();
	    }
		return list;
	}

	public static String read(InputStream in) {
		return new String(readBytes(in),StandardCharsets.UTF_8);
	}
	public static String read(InputStream in, String charset) {
		return new String(readBytes(in),Charset.forName(charset));
	}
	public static String read(InputStream in, Charset charset) {
		return new String(readBytes(in),charset);
	}

	public static InputStream stream(String data, Charset charset) {
		return new ByteArrayInputStream(data.getBytes(charset));
	}

	public static long write(InputStream in, File file) throws IOException {
		return write(in,new FileOutputStream(file));
	}
	
	public static long write(InputStream ins,OutputStream ops) throws IOException {
        return write(ops, ins, BUF_SIZE);
    }
	
	/**
     * 将输入流写入一个输出流。块大小为 8192
     * <p>
     * <b style=color:red>注意</b>，它并不会关闭输入/出流
     * 
     * @param ops
     *            输出流
     * @param ins
     *            输入流
     * 
     * @return 写入的字节数
     * @throws IOException
     */
    public static long write(OutputStream ops, InputStream ins) throws IOException {
        return write(ops, ins, BUF_SIZE);
    }
    
    /**
     * 将输入流写入一个输出流。
     * <p>
     * <b style=color:red>注意</b>，它并不会关闭输入/出流
     * 
     * @param ops
     *            输出流
     * @param ins
     *            输入流
     * @param bufferSize
     *            缓冲块大小
     * 
     * @return 写入的字节数
     * 
     * @throws IOException
     */
    public static long write(OutputStream ops, InputStream ins, int bufferSize) throws IOException {
        if (null == ops || null == ins)
            return 0;

        byte[] buf = new byte[bufferSize];
        int len;
        long bytesCount = 0;
        while (-1 != (len = ins.read(buf))) {
            bytesCount += len;
            ops.write(buf, 0, len);
        }
        // 啥都没写，强制触发一下写
        // 这是考虑到 walnut 的输出流实现，比如你写一个空文件
        // 那么输入流就是空的，但是 walnut 的包裹输出流并不知道你写过了
        // 它人你就是打开一个输出流，然后再关上，所以自然不会对内容做改动
        // 所以这里触发一个写，它就知道，喔你要写个空喔。
        if (0 == bytesCount) {
            ops.write(buf, 0, 0);
        }
        ops.flush();
        return bytesCount;
    }

	public static InputStream fin(File file) {
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	public static OutputStream fot(File file) {
		try {
			return new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void writeAndClose(Writer writer, CharSequence cs) {
        try {
            write(writer, cs);
        }
        finally {
        	flush(writer);
            close(writer);
        }
    }
	/**
     * 将一段文本全部写入一个writer。
     * <p>
     * <b style=color:red>注意</b>，它并不会关闭输出流
     * 
     * @param writer
     * 
     * @param cs
     *            文本
     * @throws IOException
     */
    public static void write(Writer writer, CharSequence cs) {
        if (null != cs && null != writer) {
        	try {
        		writer.write(cs.toString());
                writer.flush();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
        }
    }
	
	/**
     * 将输入流写入一个输出流。块大小为 8192
     * <p>
     * <b style=color:red>注意</b>，它会关闭输入/出流
     * 
     * @param ops
     *            输出流
     * @param ins
     *            输入流
     * @return 写入的字节数
     */
    public static long writeAndClose(OutputStream ops, InputStream ins) {
        try {
            return write(ops, ins);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
        	flush(ops);
            close(ops);
            close(ins);
        }
    }
    
    public static long writeAndClose(InputStream ins,File f) {
    	try {
			return writeAndClose(new FileOutputStream(f), ins);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
    }
    
    /**
     * 将文本输入流写入一个文本输出流。块大小为 8192
     * <p>
     * <b style=color:red>注意</b>，它会关闭输入/出流
     * 
     * @param writer
     *            输出流
     * @param reader
     *            输入流
     */
    public static long writeAndClose(Writer writer, Reader reader) {
        try {
            return write(writer, reader);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
        	flush(writer);
            close(writer);
            close(reader);
        }
    }
    
    /**
     * 将一个字节数组写入一个输出流。
     * <p>
     * <b style=color:red>注意</b>，它会关闭输出流
     * 
     * @param ops
     *            输出流
     * @param bytes
     *            字节数组
     */
    public static void writeAndClose(OutputStream ops, byte[] bytes) {
        try {
            write(ops, bytes);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
        	flush(ops);
            close(ops);
        }
    }
    
    /**
     * 安全刷新一个可刷新的对象，可接受 null
     * 
     * @param fa
     *            可刷新对象
     */
    public static void flush(Flushable fa) {
        if (null != fa)
            try {
                fa.flush();
            }
            catch (IOException e) {}
    }

	public static String nextLineTrim(BufferedReader br) throws IOException {
        String line = null;
        while (br.ready()) {
            line = br.readLine();
            if (line == null)
                break;
            if (Strings.isBlank(line))
                continue;
            return line.trim();
        }
        return line;
    }

	public static void appendWriteAndClose(File f, String text) {
		FileWriter fw = null;
        try {
            fw = new FileWriter(f, true);
            fw.write(text);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            close(fw);
        }
	}

	public static OutputStream fos(File dest) {
		try {
			return new FileOutputStream(dest);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	public static String readAndClose(InputStream in) {
		return readAndClose(in, StandardCharsets.UTF_8);
	}
	public static String readAndClose(InputStream in, String charset) {
		try {
			return new String(readBytes(in),Charset.forName(charset));
		} finally {
			close(in);
		}
	}
	public static String readAndClose(InputStream in, Charset charset) {
		try {
			return new String(readBytes(in),charset);
		} finally {
			close(in);
		}
	}
	public static void writeAndClose(File f, CharSequence cs) {
		writeAndClose(fos(f), cs);
	}
	public static void write(OutputStream ops, CharSequence cs) {
		try {
			write(ops, cs.toString().getBytes(StandardCharsets.UTF_8));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	public static void writeAndClose(OutputStream ops, CharSequence cs) {
		writeAndClose(ops, cs.toString().getBytes(StandardCharsets.UTF_8));
	}
	
	public static String asString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copy(inputStream, baos, true);
        return baos.toString();
    }
	
	public static String asString(InputStream inputStream, String encoding) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copy(inputStream, baos, true);
        return baos.toString(encoding);
    }
	
	public static long copy(InputStream inputStream,
            OutputStream outputStream, boolean closeOutputStream,
            byte[] buffer)
    throws IOException {
        OutputStream out = outputStream;
        InputStream in = inputStream;
        try {
            long total = 0;
            for (;;) {
                int res = in.read(buffer);
                if (res == -1) {
                    break;
                }
                if (res > 0) {
                    total += res;
                    if (out != null) {
                        out.write(buffer, 0, res);
                    }
                }
            }
            if (out != null) {
                if (closeOutputStream) {
                    out.close();
                } else {
                    out.flush();
                }
                out = null;
            }
            in.close();
            in = null;
            return total;
        } finally {
            close(in);
            if (closeOutputStream) {
            	close(out);
            }
        }
    }
	
	public static long copy(InputStream inputStream, OutputStream outputStream, boolean closeOutputStream)
            throws IOException {
        return copy(inputStream, outputStream, closeOutputStream, new byte[BUF_SIZE]);
    }
	
	public static String checkFileName(String fileName) {
        if (fileName != null  &&  fileName.indexOf('\u0000') != -1) {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0;  i < fileName.length();  i++) {
                char c = fileName.charAt(i);
                switch (c) {
                    case 0:
                        sb.append("\\0");
                        break;
                    default:
                        sb.append(c);
                        break;
                }
            }
            throw new RuntimeException(fileName+
                    "Invalid file name: " + sb);
        }
        return fileName;
    }

	public static void readFully(final InputStream input, final byte[] buffer) throws IOException {
        int length=buffer.length;
        final int actual = read(input, buffer, 0,length);
        if (actual != length) {
            throw new EOFException("Length to read: " + length + " actual: " + actual);
        }
    }
	
	public static int read(final InputStream input, final byte[] buffer, final int offset, final int length)
            throws IOException {
        if (length < 0) {
            throw new IllegalArgumentException("Length must not be negative: " + length);
        }
        int remaining = length;
        while (remaining > 0) {
            final int location = length - remaining;
            final int count = input.read(buffer, offset + location, remaining);
            if (-1 == count) { // EOF
                break;
            }
            remaining -= count;
        }
        return length - remaining;
    }
	
	
	
	public static Map<String, String> resource(String path) {
		try {
			return resource(new InputStreamReader(Streams.class.getResourceAsStream(path), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			return new HashMap<String, String>();
		}
	}
	
	public static Map<String, String> resource(Reader reader) {
        Map<String, String> map = new ConcurrentHashMap<String, String>();
        try {
            BufferedReader br = new BufferedReader(reader);
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] tokens = line.trim().split("=");
                map.put(tokens[0], tokens[1]);
            }
            br.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

	/**
	 * 从输入流中读取指定长度的数据
	 */
	public static byte[] readStream(InputStream is, String isName, byte[] buf, int len) throws IOException
	{
		for (int n = 0; n < len;)
		{
			int r = is.read(buf, n, len - n);
			if (r <= 0)
				throw new IOException(String.format("read interrupt(%s:%d/%d)", isName, n, len));
			n += r;
		}
		return buf;
	}

	public static long copyAndClose(InputStream in, OutputStream out) {
		try {
			return copy(in, out);
		} finally {
			close(in,out);
		}
	}

	  /**
	   * 读完流且不处理
	   *
	   * @param input 输入流
	   * @return 总字节数
	   * @throws IOException io异常
	   */
	  public static long drain(InputStream input) throws IOException {
	    long byteCount = 0;
	    if (input == null) {
	      return byteCount;
	    }
	    byte[] buffer = new byte[BUF_SIZE];
	    int bytesRead;
	    while ((bytesRead = input.read(buffer)) != -1) {
	      byteCount += bytesRead;
	    }
	    return byteCount;
	  }

//	  /**
//	   * copy
//	   *
//	   * @param input 输入流
//	   * @param bytes 字节组
//	   * @return 总字节数
//	   * @throws IOException io异常
//	   */
//	  public static long copy(InputStream input, byte[] bytes) throws IOException {
//		  byte[] buffer = new byte[BUFFER_SIZE];
//		  ByteArrayOutputStream bis=new ByteArrayOutputStream(bytes.length);
//		    long count = 0;
//		    int bytesRead;
//		    while ((bytesRead = input.read(buffer)) != -1) {
//		    	bis.write(buffer, 0, bytesRead);
//		      count += bytesRead;
//		    }
//		  return count;
//	  }

	  /**
	   * 输入流转byte[]
	   *
	   * @param input 输入流
	   * @return byte[]
	   * @throws IOException io异常
	   */
	  public static byte[] toBytes(InputStream in) throws IOException {
		  ByteArrayOutputStream output = new ByteArrayOutputStream();
	        byte[] buffer = new byte[BUF_SIZE];
	        int n = 0;
	        try {
	        	while (-1 != (n = in.read(buffer))) {
	                output.write(buffer, 0, n);
	            }
	            return output.toByteArray();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
	  }

	  /**
	   * 输入流转字符串
	   *
	   * @param input 输入流
	   * @return 字符串
	   * @throws IOException io异常
	   */
	  public static String toString(InputStream input) throws IOException {
	    ByteArrayOutputStream output = new ByteArrayOutputStream();
	    copy(input, output);
	    return output.toString();
	  }

	  /**
	   * 输入流转字符串
	   *
	   * @param input 输入流
	   * @param charset 字符集
	   * @return 字符串
	   * @throws IOException io异常
	   */
	  public static String toString(InputStream input, Charset charset) throws IOException {
	    ByteArrayOutputStream output = new ByteArrayOutputStream();
	    copy(input, output);
	    return output.toString(charset.name());
	  }

	  /**
	   * 合并buffer
	   *
	   * @param buffers buffer集合
	   * @return 合并后的buffer
	   */
	  public static ByteBuffer composite(List<ByteBuffer> buffers) {
	    int capacity = 0;
	    for (ByteBuffer buffer : buffers) {
	      capacity += buffer.remaining();
	    }
	    ByteBuffer ret = ByteBuffer.allocate(capacity);
	    for (ByteBuffer buffer : buffers) {
	      ret.put(buffer);
	    }
	    ret.position(0);
	    ret.limit(ret.capacity());
	    return ret;
	  }

	public static byte[] readBytes(String path) {
		try {
			return Jse.clazz.getResourceAsStream(path).readAllBytes();
		} catch (IOException e) {
			e.printStackTrace();
			return new byte[0];
		}
	}

	public static InputStream fileInput(File file) {
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	public static InputStream classInput(String path) {
		InputStream in=Streams.class.getResourceAsStream(path);
		if(in==null) {
			in=Jse.clazz.getClassLoader().getResourceAsStream(path);
		}
		return in;
	}

	//获取覆盖输出pw
    public static PrintWriter printWriter(File file) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return pw;
    }
    
  //获取追加输出pw
    public static PrintWriter printWriter(File file,boolean append) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new FileOutputStream(file,append));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return pw;
    }
}
